package jgl.vajra.kingkong.widget;


import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.logger.Logger;

import jgl.android.loadinglibrary.LoadingIndicatorView;
import jgl.vajra.kingkong.R;
import jgl.vajra.kingkong.databinding.ActivityBigImagePagerBinding;
import jgl.vajra.kingkong.databinding.ItemPagerImageBinding;
import jgl.vajra.kingkong.widget.base.BaseViewPagerAdapter;

import jgl.vajra.kingkong.widget.utils.BitmapUtils;
import jgl.vajra.kingkong.widget.utils.DisplayUtils;
import jgl.vajra.kingkong.widget.utils.FileUtils;
import jgl.vajra.kingkong.widget.utils.MD5Utils;
import jgl.vajra.kingkong.widget.utils.ToastUtils;
import jgl.vajra.kingkong.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.kingkong.widget.databindingadapter.BaseDataBindingDecorator;
import jgl.vajra.kingkong.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.kingkong.widget.mvvm.view.BaseMVVMView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 查看大图 glide
 */
public class BigImagePagerActivity extends BaseMVVMActivity implements BaseMVVMView, BaseViewPagerAdapter.BaseViewPageItemDecorator<String, ItemPagerImageBinding>, BaseViewPagerAdapter.BaseViewPageItemPresenter<String>, BaseDataBindingDecorator<String, ItemPagerImageBinding>, BaseBindingItemPresenter {
    public static final String INTENT_IMG_URLS = "imgUrls";
    public static final String INTENT_POSITION = "position";
    public static final String INTENT_IAG_TYPE = "imageType";
    ActivityBigImagePagerBinding binding;
    private List<View> pointViewList;
    private int imageType;
    public static final int TYPE_NET_IMAGE = 1;
    public static final int TYPE_FILE_IMAGE = 2;

    @Override
    public int getLayoutId() {
        return R.layout.activity_big_image_pager;
    }

    @Override
    protected int getStateBarColor() {
        return R.color.transparent;
    }

    @Override
    public void initView() {
        binding = (ActivityBigImagePagerBinding) mBinding;
        List<String> imgUrls = (List<String>) getIntent().getSerializableExtra(INTENT_IMG_URLS);
        Logger.d("BigImagePagerActivity imgUrls" + imgUrls.toString());
        int startPosition = getIntent().getIntExtra(INTENT_POSITION, 0);
        imageType = getIntent().getIntExtra(INTENT_IAG_TYPE, 1);
        binding.setView(this);
        pointViewList = new ArrayList<>();
        addGuidePointView(startPosition, imgUrls);
        BaseViewPagerAdapter adapter = new BaseViewPagerAdapter(imgUrls) {
            @Override
            public View getRootView() {
                return View.inflate(BigImagePagerActivity.this, R.layout.item_pager_image, null);
            }
        };
        adapter.setItemPresenter(this);
        adapter.setItemDecorator(this);
        binding.pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                for (View view : pointViewList) {
                    view.setSelected(false);
                }
                pointViewList.get(position).setSelected(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        binding.pager.setOffscreenPageLimit(2);
        binding.pager.setAdapter(adapter);
        binding.pager.setCurrentItem(startPosition);
    }

    private void addGuidePointView(int startPosition, List<String> imgUrls) {
        if (imgUrls != null && imgUrls.size() > 0) {
            pointViewList.clear();
            for (int i = 0; i < imgUrls.size(); i++) {
                if (!TextUtils.isEmpty(imgUrls.get(i))) {
                    View view = new View(this);
                    view.setBackgroundResource(R.drawable.selector_guide_bg);
                    view.setSelected(i == startPosition);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(8),
                            DisplayUtils.dip2px(8));
                    layoutParams.setMargins(20, 0, 0, 0);
                    binding.guideGroup.addView(view, layoutParams);
                    pointViewList.add(view);
                }
            }
        }

    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }


    @Override
    protected boolean isNeedLoadStatusBar() {
        return false;
    }

    @Override
    public boolean isUseProxy() {
        return false;
    }

    @Override
    public void decorator(ItemPagerImageBinding itemBinding, int position, int viewType, String data) {

        if (imageType == TYPE_NET_IMAGE) {
            showNetImage(data, itemBinding);

        } else {
            lookFileImage(data, itemBinding);
        }

    }


    private void lookFileImage(final String imgurl, ItemPagerImageBinding itemBinding) {

        File file = new File(imgurl);
        float initImageScale = BitmapUtils.getInitImageScale(file.getAbsolutePath(), BigImagePagerActivity.this);
        itemBinding.image.setMaxScale(initImageScale + 2.0f);//最大显示比例
        itemBinding.image.setImage(ImageSource.uri(Uri.fromFile(file)), new ImageViewState(initImageScale, new PointF(0, 0), 0));
    }

    private void showNetImage(final String imgUrl, ItemPagerImageBinding itemBinding) {
        Glide.with(BigImagePagerActivity.this).asBitmap().load(imgUrl).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                itemBinding.loading.smoothToHide();
                if (resource == null) return;
                float initImageScale = BitmapUtils.getInitImageScale(resource, BigImagePagerActivity.this);
                itemBinding.image.setMaxScale(initImageScale + 2.0f);//最大显示比例
                itemBinding.image.setImage(ImageSource.bitmap(resource), new ImageViewState(initImageScale, new PointF(0, 0), 0));
                itemBinding.image.setVisibility(View.VISIBLE);
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                itemBinding.loading.smoothToHide();
                itemBinding.image.setImage(ImageSource.resource(R.drawable.ic_big_image_error));
            }
        });


    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.overridePendingTransition(R.anim.fade_in,
                R.anim.fade_out);

    }

    @Override
    public void finish() {
        super.finish();
        this.overridePendingTransition(R.anim.act_fade_in_center,
                R.anim.act_fade_out_center);
    }

    @Override
    public void onViewPageItemClick(int position, String itemData) {

    }


    @Override
    public void onItemClick(int position, Object itemData) {

    }

    public void onSaveImage(int position, String itemData) {
        if (imageType == TYPE_NET_IMAGE) {
            Glide.with(BigImagePagerActivity.this).asBitmap().load(itemData).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    BitmapUtils.saveFile(resource, MD5Utils.encode(itemData) + "." + FileUtils.getExtension(itemData),
                            BigImagePagerActivity.this);
                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                    super.onLoadFailed(errorDrawable);

                }
            });

        } else {
            ToastUtils.showShort("图片保存于" + new File(itemData).getAbsolutePath());
        }
    }
}